package cn.cosmosx.base.validate;

import cn.cosmosx.base.util.check.OrgCodeCheckUtil;
import org.apache.commons.lang3.StringUtils;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.*;

/**
 * 组织机构代码校验注解
 * <p>
 * message，groups，payload三个属性必须包含，其他的自定义
 *
 * @author gengzhy
 */
@Target({ElementType.METHOD, ElementType.FIELD,
        ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Constraint(validatedBy = OrgCode.Validator.class)
public @interface OrgCode {
    /**
     * 是否必须
     */
    boolean required() default true;

    /**
     * 校验不通过返回的提示信息
     */
    String message() default "组织机构代码不合法";

    /**
     * Constraint要求的属性，用于分组校验和扩展，留空就好
     */
    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    class Validator extends AbstractValidator implements ConstraintValidator<OrgCode, CharSequence> {
        private OrgCode orgCode;

        @Override
        public void initialize(OrgCode constraintAnnotation) {
            this.orgCode = constraintAnnotation;
        }

        @Override
        public boolean isValid(CharSequence value, ConstraintValidatorContext context) {
            if (orgCode.required() && StringUtils.isBlank(value)) {
                setTemplateMessage("组织机构代码不能为空", context);
                return false;
            }
            if (!validate(value)) {
                setTemplateMessage(orgCode.message(), context);
                return false;
            }
            return true;
        }

        private boolean validate(CharSequence orgCode) {
            return OrgCodeCheckUtil.verify((String) orgCode);
        }

    }
}
